package com.zd.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()//从内存中读取认证信息
                .passwordEncoder(new BCryptPasswordEncoder())//设置加密器-Bcrypt
        .withUser("admin")//自定义用户
        .password(new BCryptPasswordEncoder().encode("admin"))//自定义密码-加密器加密
        .roles("admin");//权限
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/","/index/**","/logout")//放行的路径
                .permitAll()//所有人都可访问
                .anyRequest()//其他资源
                .authenticated()//认证通过方可访问
                .and()//开始其他的配置
                .formLogin()//自定义登录表单
                .loginPage("/")//设置登陆页面
                .loginProcessingUrl("/login")//表单提交的url
                .usernameParameter("uname")//自定义用户名参数-默认为username
                .passwordParameter("upwd")//自定义用户密码-默认password
                .defaultSuccessUrl("/news/list")//登陆成功，默认跳转页面
                .permitAll()
                .and()
                .logout()
                    .logoutUrl("/logout")//退出路径
                .logoutSuccessUrl("/")//推出成功的路径
                .deleteCookies("JSESSIONID")
                .permitAll()
        ;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**","/images/**","/js/**");
    }
}
